
<!DOCTYPE html><html lang="zh-CN">

<head>
  <meta charset="utf-8">
  <meta name="hexo-theme" content="https://github.com/xaoxuu/hexo-theme-stellar/tree/1.29.1" theme-name="Stellar" theme-version="1.29.1">
  
  <meta name="generator" content="Hexo 7.1.1">
  <meta http-equiv='x-dns-prefetch-control' content='on' />
  
  <meta name="renderer" content="webkit">
  <meta name="force-rendering" content="webkit">
  <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
  <meta name="HandheldFriendly" content="True" >
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="theme-color" media="(prefers-color-scheme: dark)" content="#000">
  <meta name="theme-color" content="#f9fafb">
  
  <title>SpringBoot大文件上传 - Sentry's Blog</title>

  
    <meta name="description" content="大文件上传">
<meta property="og:type" content="article">
<meta property="og:title" content="SpringBoot大文件上传">
<meta property="og:url" content="https://coclong.gitee.io/2023/09/24/practice/SpringBoot%E5%A4%A7%E6%96%87%E4%BB%B6%E4%B8%8A%E4%BC%A0/index.html">
<meta property="og:site_name" content="Sentry&#39;s Blog">
<meta property="og:description" content="大文件上传">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://coclong.gitee.io/images/study/java/202309242223.jpg">
<meta property="og:image" content="https://bu.dusays.com/2022/10/24/63567d3e07da3.png">
<meta property="og:image" content="https://bu.dusays.com/2022/10/24/63567d3e07da3.png">
<meta property="article:published_time" content="2023-09-24T13:46:00.000Z">
<meta property="article:modified_time" content="2024-03-10T11:50:36.088Z">
<meta property="article:author" content="sentry">
<meta property="article:tag" content="Java">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://coclong.gitee.io/images/study/java/202309242223.jpg">
  
  
  
  <meta name="keywords" content="Java">

  <!-- feed -->
  

  <link rel="stylesheet" href="/css/main.css?v=1.29.1">

  
    <link rel="shortcut icon" href="https://foruda.gitee.com/avatar/1677090168613487741/7674882_coclong_1619494197.png!avatar200">
  

  

  
</head>
<body>

<div class="l_body s:aa content tech" id="start" layout="post" ><aside class="l_left"><div class="leftbar-container">


<header class="header"><div class="logo-wrap"><a class="avatar" href="/about/"><div class="bg" style="opacity:0;background-image:url(https://gcore.jsdelivr.net/gh/cdn-x/placeholder@1.0.12/avatar/round/rainbow64@3x.webp);"></div><img no-lazy class="avatar" src="https://q1.qlogo.cn/g?b=qq&nk=2930811148&s=100" onerror="javascript:this.classList.add('error');this.src='https://gcore.jsdelivr.net/gh/cdn-x/placeholder@1.0.12/image/2659360.svg';"></a><a class="title" href="/"><div class="main" ff="title">Sentry's Blog</div><div class="sub normal cap">被人记住的感觉真好啊</div><div class="sub hover cap" style="opacity:0">孤独伴我同行</div></a></div></header>

<div class="nav-area">
<div class="search-wrapper" id="search-wrapper"><form class="search-form"><a class="search-button" onclick="document.getElementById(&quot;search-input&quot;).focus();"><svg t="1705074644177" viewBox="0 0 1025 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="1560" width="200" height="200"><path d="M1008.839137 935.96571L792.364903 719.491476a56.783488 56.783488 0 0 0-80.152866 0 358.53545 358.53545 0 1 1 100.857314-335.166073 362.840335 362.840335 0 0 1-3.689902 170.145468 51.248635 51.248635 0 1 0 99.217358 26.444296 462.057693 462.057693 0 1 0-158.255785 242.303546l185.930047 185.725053a51.248635 51.248635 0 0 0 72.568068 0 51.248635 51.248635 0 0 0 0-72.978056z" p-id="1561"></path><path d="M616.479587 615.969233a50.428657 50.428657 0 0 0-61.498362-5.534852 174.655348 174.655348 0 0 1-177.525271 3.484907 49.403684 49.403684 0 0 0-58.833433 6.76482l-3.074918 2.869923a49.403684 49.403684 0 0 0 8.609771 78.10292 277.767601 277.767601 0 0 0 286.992355-5.739847 49.403684 49.403684 0 0 0 8.404776-76.667958z" p-id="1562"></path></svg></a><input type="text" class="search-input" id="search-input" placeholder="站内搜索"></form><div id="search-result"></div><div class="search-no-result">没有找到内容！</div></div>


<nav class="menu dis-select"><a class="nav-item active" title="文章" href="/" style="color:#1BCDFC"><svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24"><path fill="currentColor" fill-rule="evenodd" d="M5.879 2.879C5 3.757 5 5.172 5 8v8c0 2.828 0 4.243.879 5.121C6.757 22 8.172 22 11 22h2c2.828 0 4.243 0 5.121-.879C19 20.243 19 18.828 19 16V8c0-2.828 0-4.243-.879-5.121C17.243 2 15.828 2 13 2h-2c-2.828 0-4.243 0-5.121.879M8.25 17a.75.75 0 0 1 .75-.75h3a.75.75 0 0 1 0 1.5H9a.75.75 0 0 1-.75-.75M9 12.25a.75.75 0 0 0 0 1.5h6a.75.75 0 0 0 0-1.5zM8.25 9A.75.75 0 0 1 9 8.25h6a.75.75 0 0 1 0 1.5H9A.75.75 0 0 1 8.25 9" clip-rule="evenodd"/><path fill="currentColor" d="M5.235 4.058C5 4.941 5 6.177 5 8v8c0 1.823 0 3.058.235 3.942L5 19.924c-.975-.096-1.631-.313-2.121-.803C2 18.243 2 16.828 2 14v-4c0-2.829 0-4.243.879-5.121c.49-.49 1.146-.707 2.121-.803zm13.53 15.884C19 19.058 19 17.822 19 16V8c0-1.823 0-3.059-.235-3.942l.235.018c.975.096 1.631.313 2.121.803C22 5.757 22 7.17 22 9.999v4c0 2.83 0 4.243-.879 5.122c-.49.49-1.146.707-2.121.803z" opacity=".5"/></svg></a><a class="nav-item" title="项目" href="/wiki/" style="color:#3DC550"><svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24"><path fill="currentColor" fill-rule="evenodd" d="M14.25 4.48v3.057c0 .111 0 .27.02.406a.936.936 0 0 0 .445.683a.96.96 0 0 0 .783.072c.13-.04.272-.108.378-.159L17 8.005l1.124.534c.106.05.248.119.378.16a.958.958 0 0 0 .783-.073a.936.936 0 0 0 .444-.683c.021-.136.021-.295.021-.406V3.031c.113-.005.224-.01.332-.013C21.154 2.98 22 3.86 22 4.933v11.21c0 1.112-.906 2.01-2.015 2.08c-.97.06-2.108.179-2.985.41c-1.082.286-1.99 1.068-3.373 1.436c-.626.167-1.324.257-1.627.323V5.174c.32-.079 1.382-.203 1.674-.371c.184-.107.377-.216.576-.323m5.478 8.338a.75.75 0 0 1-.546.91l-4 1a.75.75 0 0 1-.364-1.456l4-1a.75.75 0 0 1 .91.546" clip-rule="evenodd"/><path fill="currentColor" d="M18.25 3.151c-.62.073-1.23.18-1.75.336a8.2 8.2 0 0 0-.75.27v3.182l.75-.356l.008-.005a1.13 1.13 0 0 1 .492-.13c.047 0 .094.004.138.01c.175.029.315.1.354.12l.009.005l.749.356V3.647z"/><path fill="currentColor" d="M12 5.214c-.334-.064-1.057-.161-1.718-.339C8.938 4.515 8.05 3.765 7 3.487c-.887-.234-2.041-.352-3.018-.412C2.886 3.007 2 3.9 2 4.998v11.146c0 1.11.906 2.01 2.015 2.079c.97.06 2.108.179 2.985.41c.486.129 1.216.431 1.873.726c1.005.451 2.052.797 3.127 1.034z" opacity=".5"/><path fill="currentColor" d="M4.273 12.818a.75.75 0 0 1 .91-.545l4 1a.75.75 0 1 1-.365 1.455l-4-1a.75.75 0 0 1-.545-.91m.909-4.545a.75.75 0 1 0-.364 1.455l4 1a.75.75 0 0 0 .364-1.455z"/></svg></a><a class="nav-item" title="便笺" href="/notes/" style="color:#FA6400"><svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24"><path fill="currentColor" d="M20 12a8 8 0 1 1-16 0a8 8 0 0 1 16 0" opacity=".5"/><path fill="currentColor" d="M17.712 5.453c1.047-.193 2.006-.259 2.797-.152c.77.103 1.536.393 1.956 1.064c.446.714.312 1.542-.012 2.258c-.33.728-.918 1.499-1.672 2.268c-1.516 1.547-3.836 3.226-6.597 4.697c-2.763 1.472-5.495 2.484-7.694 2.92c-1.095.217-2.098.299-2.923.201c-.8-.095-1.6-.383-2.032-1.075c-.47-.752-.296-1.63.07-2.379c.375-.768 1.032-1.586 1.872-2.403L4 12.416c0 .219.083.71.168 1.146c.045.23.09.444.123.596c-.652.666-1.098 1.263-1.339 1.756c-.277.567-.208.825-.145.925c.072.116.305.305.937.38c.609.073 1.44.018 2.455-.183c2.02-.4 4.613-1.351 7.28-2.772c2.667-1.42 4.85-3.015 6.23-4.423c.694-.707 1.15-1.334 1.377-1.836c.233-.515.167-.75.107-.844c-.07-.112-.289-.294-.883-.374c-.542-.072-1.272-.041-2.163.112L16.87 5.656c.338-.101.658-.17.842-.203"/></svg></a><a class="nav-item" title="更多" href="/more/" style="color:#F44336"><svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24"><path fill="currentColor" d="m13.629 20.472l-.542.916c-.483.816-1.69.816-2.174 0l-.542-.916c-.42-.71-.63-1.066-.968-1.262c-.338-.197-.763-.204-1.613-.219c-1.256-.021-2.043-.098-2.703-.372a5 5 0 0 1-2.706-2.706C2 14.995 2 13.83 2 11.5v-1c0-3.273 0-4.91.737-6.112a5 5 0 0 1 1.65-1.651C5.59 2 7.228 2 10.5 2h3c3.273 0 4.91 0 6.113.737a5 5 0 0 1 1.65 1.65C22 5.59 22 7.228 22 10.5v1c0 2.33 0 3.495-.38 4.413a5 5 0 0 1-2.707 2.706c-.66.274-1.447.35-2.703.372c-.85.015-1.275.022-1.613.219c-.338.196-.548.551-.968 1.262" opacity=".5"/><path fill="currentColor" d="M10.99 14.308c-1.327-.978-3.49-2.84-3.49-4.593c0-2.677 2.475-3.677 4.5-1.609c2.025-2.068 4.5-1.068 4.5 1.609c0 1.752-2.163 3.615-3.49 4.593c-.454.335-.681.502-1.01.502c-.329 0-.556-.167-1.01-.502"/></svg></a></nav>
</div>
<div class="widgets">


<widget class="widget-wrapper post-list"><div class="widget-header dis-select"><span class="name">最近更新</span></div><div class="widget-body fs14"><a class="item title" href="/2023/07/16/base/%E5%86%99%E4%BD%9C%E5%A7%BF%E5%8A%BF/"><span class="title">写作姿势</span></a><a class="item title" href="/2023/07/11/base/%E5%B8%B8%E7%94%A8%E8%BD%AF%E4%BB%B6/"><span class="title">常用软件</span></a><a class="item title" href="/2023/07/28/base/%E5%8D%9A%E5%AE%A2%E7%BE%8E%E5%8C%96/"><span class="title">博客美化</span></a><a class="item title" href="/2024/04/27/other/%E7%BD%91%E7%BB%9C%E6%97%A5%E5%BF%97/"><span class="title">一周是一年的2%</span></a><a class="item title" href="/2023/08/09/other/%E5%A4%A7%E5%AD%A6%E4%B8%8A%E5%88%B0%E7%8E%B0%E5%9C%A8%E7%BB%88%E4%BA%8E%E6%98%8E%E7%99%BD%E7%9A%84%E4%BA%8B/"><span class="title">大学上到现在终于明白的事</span></a><a class="item title" href="/2023/08/13/study/Java%E4%BB%A3%E7%A0%81%E7%B2%BE%E7%AE%80%E6%8C%87%E5%8D%97/"><span class="title">Java代码精简指南</span></a><a class="item title" href="/2023/06/18/base/Hexo%E6%90%AD%E5%BB%BA%E5%8D%9A%E5%AE%A2%E4%B9%8B%E8%B7%AF/"><span class="title">Hexo搭建博客之路</span></a><a class="item title" href="/2023/09/07/other/%E6%B8%B8%E9%BE%99%E5%BD%93%E5%BD%92%E6%B5%B7/"><span class="title">游龙当归海，海不迎我自来也</span></a><a class="item title" href="/2023/10/02/other/%E8%80%83%E9%A9%BE%E7%85%A7%E7%9A%84%E9%82%A3%E4%BA%9B%E4%BA%8B%E5%84%BF/"><span class="title">考驾照的那些事儿</span></a><a class="item title" href="/2024/01/15/other/%E9%80%89%E6%8B%A9/"><span class="title">找工作</span></a></div></widget>
</div>
<footer class="footer dis-select"><div class="social-wrap"><a class="social" href="https://gitee.com/coclong" target="_blank" rel="external nofollow noopener noreferrer"><img class="lazy" src="" data-src="https://gcore.jsdelivr.net/gh/cdn-x/placeholder@1.0.12/social/08a41b181ce68.svg"/></a><a class="social" href="https://wpa.qq.com/msgrd?v=3&uin=2930811148&site=qq&menu=yes&jumpflag=1" target="_blank" rel="external nofollow noopener noreferrer"><img class="lazy" src="" data-src="/images/footer/qq32.svg"/></a><a class="social" href="/" rel="noopener noreferrer"><img class="lazy" src="" data-src="https://gcore.jsdelivr.net/gh/cdn-x/placeholder@1.0.12/social/3616429.svg"/></a><a class="social" href="/more" rel="noopener noreferrer"><img class="lazy" src="" data-src="https://gcore.jsdelivr.net/gh/cdn-x/placeholder@1.0.12/social/942ebbf1a4b91.svg"/></a></div></footer>
</div></aside><div class="l_main" id="main">





<div class="article banner top">
  <div class="content">
    <div class="top bread-nav footnote"><div class="left"><div class="flex-row" id="breadcrumb"><a class="cap breadcrumb" href="/">主页</a>
<span class="sep"></span><a class="cap breadcrumb" href="/">文章</a><span class="sep"></span><a class="cap breadcrumb-link" href="/categories/%E6%8A%80%E8%83%BD/">技能</a></div>
<div class="flex-row" id="post-meta"><span class="text created">发布于：<time datetime="2023-09-24T13:46:00.000Z">2023-09-24</time></span><span class="sep updated"></span><span class="text updated">更新于：<time datetime="2024-03-10T11:50:36.088Z">2024-03-10</time></span></div></div></div>
    
    <div class="bottom only-title">
      
      <div class="text-area">
        <h1 class="text title"><span>SpringBoot大文件上传</span></h1>
        
      </div>
    </div>
    
  </div>
  </div><article class="md-text content"><a class="tag-plugin colorful hashtag" color="red" target="_blank" rel="noopener" href="https://gitee.com/coclong/bigfile-upload"><svg t="1701408144765" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="4228" width="200" height="200"><path d="M426.6 64.8c34.8 5.8 58.4 38.8 52.6 73.6l-19.6 117.6h190.2l23-138.6c5.8-34.8 38.8-58.4 73.6-52.6s58.4 38.8 52.6 73.6l-19.4 117.6H896c35.4 0 64 28.6 64 64s-28.6 64-64 64h-137.8l-42.6 256H832c35.4 0 64 28.6 64 64s-28.6 64-64 64h-137.8l-23 138.6c-5.8 34.8-38.8 58.4-73.6 52.6s-58.4-38.8-52.6-73.6l19.6-117.4h-190.4l-23 138.6c-5.8 34.8-38.8 58.4-73.6 52.6s-58.4-38.8-52.6-73.6l19.4-117.8H128c-35.4 0-64-28.6-64-64s28.6-64 64-64h137.8l42.6-256H192c-35.4 0-64-28.6-64-64s28.6-64 64-64h137.8l23-138.6c5.8-34.8 38.8-58.4 73.6-52.6z m11.6 319.2l-42.6 256h190.2l42.6-256h-190.2z" p-id="4229"></path></svg><span>MyGitee</span></a>

<h2 id="介绍"><a href="#介绍" class="headerlink" title="介绍"></a>介绍</h2><h3 id="分片上传"><a href="#分片上传" class="headerlink" title="分片上传"></a>分片上传</h3><p><strong>分片上传</strong>就是将所要上传的文件，按照一定的大小，将整个文件分隔成多个数据块（我们称之为 <code>Part</code>）来进行分别上传，上传完之后再由服务端对所有上传的文件进行汇总整合成原始的文件。</p>
<p><strong>小文件（图片、文档、视频）上传</strong>可以直接使用很多 <code>ui</code> 框架封装的上传组件，或者自己写一个 <code>input</code>  上传，利用 <code>FormData</code>  对象提交文件数据，后端使用 <code>Spring</code> 提供的 <code>MultipartFile</code> 进行文件的接收，然后写入即可。但是对于比较大的文件，比如上传2G左右的文件（http上传），就需要将文件分片上传（借助于 <code>file.slice()</code> ），否则中间 http 长时间连接可能会断掉。</p>
<h3 id="断点续传"><a href="#断点续传" class="headerlink" title="断点续传"></a>断点续传</h3><p><strong>断点续传</strong>是在下载或上传时，将下载或上传任务（一个文件或一个压缩包）人为的划分为几个部分，每一个部分采用一个线程进行上传或下载，如果碰到网络故障，可以从已经上传或下载的部分开始继续上传或者下载未完成的部分，而没有必要从头开始上传或者下载。</p>
<blockquote>
<p>断点续传可以看成是分片上传的一个衍生，因此可以使用分片上传的场景，都可以使用断点续传。</p>
</blockquote>
<h4 id="核心逻辑"><a href="#核心逻辑" class="headerlink" title="核心逻辑"></a>核心逻辑</h4><p>在分片上传的过程中，如果因为系统崩溃或者网络中断等异常因素导致上传中断，这时候客户端需要记录上传的进度。在之后支持再次上传时，可以继续从上次上传中断的地方进行继续上传。</p>
<p>为了避免客户端在上传之后的进度数据被删除而导致重新开始从头上传的问题，服务端也可以提供相应的接口便于客户端对已经上传的分片数据进行查询，从而使客户端知道已经上传的分片数据，从而从下一个分片数据开始继续上传。</p>
<details class="tag-plugin colorful folding" color="orange" child="tabs" open><summary><span>整体过程</span></summary><div class="body"><ol><li><p>前端将文件按照百分比进行计算，每次按照百分比上传文件(文件分片，指定分片大小)，给文件分片做上序号</p></li><li><p>后端将前端每次上传的文件，放入到缓存目录</p></li><li><p>等待前端将全部的文件内容都上传完毕后，发送一个合并请求（后端自行判断也可）</p></li><li><p>后端使用 <code>RandomAccessFile</code> 进多线程读取所有的分片文件，一个线程一个分片</p></li><li><p>后端每个线程按照序号将分片的文件写入到目标文件中</p></li><li><p>在上传文件的过程中发生断网了或者被手动暂停了，下次上传的时候发送续传请求，让后端删除最后一个分片</p></li><li><p>前端重新发送上次的文件分片</p></li><li><p>最后上传缺少的分片即可</p></li></ol></div></details>

<h3 id="秒传"><a href="#秒传" class="headerlink" title="秒传"></a>秒传</h3><p><strong>秒传</strong>通俗地说，你把要上传的东西上传，服务器会先做MD5校验，如果服务器上有一样的东西，它就直接给你个新地址，其实你下载的都是服务器上的同一个文件，想要不秒传，其实只要让MD5改变，就是对文件本身做一下修改（改名字不行），例如一个文本文件，你多加几个字，MD5就变了，就不会秒传了。</p>
<h2 id="参数设计"><a href="#参数设计" class="headerlink" title="参数设计"></a>参数设计</h2><p><a target="_blank" rel="noopener" href="https://github.com/simple-uploader/Uploader/blob/develop/README_zh-CN.md#%E6%9C%8D%E5%8A%A1%E7%AB%AF%E5%A6%82%E4%BD%95%E6%8E%A5%E5%8F%97%E5%91%A2">参考官方文档</a></p>
<table>
<thead>
<tr>
<th>字段名</th>
<th>类型</th>
<th>释义</th>
</tr>
</thead>
<tbody><tr>
<td>chunkNumber</td>
<td>Integer</td>
<td>当前块的次序，第一个块是 1，注意不是从 0 开始的</td>
</tr>
<tr>
<td>totalChunks</td>
<td>Integer</td>
<td>文件被分成块的总数</td>
</tr>
<tr>
<td>chunkSize</td>
<td>Long</td>
<td>分块大小，根据 totalSize 和这个值就可以计算出总共的块数。<br />注意最后一块的大小可能会比这个要大</td>
</tr>
<tr>
<td>currentChunkSize</td>
<td>Long</td>
<td>当前块的大小，实际大小</td>
</tr>
<tr>
<td>totalSize</td>
<td>Long</td>
<td>文件总大小</td>
</tr>
<tr>
<td>identifier</td>
<td>String</td>
<td>这个就是每个文件的唯一标示</td>
</tr>
<tr>
<td>filename</td>
<td>Sting</td>
<td>文件名</td>
</tr>
<tr>
<td>relativePath</td>
<td>String</td>
<td>文件夹上传的时候文件的相对路径属性</td>
</tr>
<tr>
<td>file</td>
<td>MultipartFile</td>
<td>文件块</td>
</tr>
</tbody></table>
<h2 id="流程设计"><a href="#流程设计" class="headerlink" title="流程设计"></a>流程设计</h2><div class="tag-plugin image"><div class="image-bg"><img class="lazy" src="" data-src="/images/study/java/202309242223.jpg" data-fancybox="true"/><a class="image-download blur" style="opacity:0" target="_blank" href="/images/study/java/202309242223.jpg"><svg class="icon" style="width: 1em; height: 1em;vertical-align: middle;fill: currentColor;overflow: hidden;" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="3734"><path d="M561.00682908 685.55838913a111.03077546 111.03077546 0 0 1-106.8895062 0L256.23182837 487.72885783a55.96309219 55.96309219 0 0 1 79.13181253-79.18777574L450.70357448 523.88101491V181.55477937a55.96309219 55.96309219 0 0 1 111.92618438 0v344.06109173l117.07478902-117.07478901a55.96309219 55.96309219 0 0 1 79.13181252 79.18777574zM282.81429711 797.1487951h447.70473912a55.96309219 55.96309219 0 0 1 0 111.92618438H282.81429711a55.96309219 55.96309219 0 0 1 0-111.92618438z" p-id="3735"></path></svg></a></div></div>

<div class="tag-plugin link dis-select"><a class="link-card rich" title="" href="https://doc.bulkall.top/spring/big-file/#%E4%BB%80%E4%B9%88%E6%98%AF%E5%88%86%E7%89%87%E4%B8%8A%E4%BC%A0%E3%80%81%E7%A7%92%E4%BC%A0%E3%80%81%E6%96%AD%E7%82%B9%E7%BB%AD%E4%BC%A0" target="_blank" rel="external nofollow noopener noreferrer" cardlink autofill="title,icon,desc"><div class="top"><div class="lazy img" data-bg="https://gcore.jsdelivr.net/gh/cdn-x/placeholder@1.0.12/link/8f277b4ee0ecd.svg"></div><span class="cap link footnote">https://doc.bulkall.top/spring/big-file/#%E4%BB%80%E4%B9%88%E6%98%AF%E5%88%86%E7%89%87%E4%B8%8A%E4%BC%A0%E3%80%81%E7%A7%92%E4%BC%A0%E3%80%81%E6%96%AD%E7%82%B9%E7%BB%AD%E4%BC%A0</span></div><div class="bottom"><span class="title">https://doc.bulkall.top/spring/big-file/#%E4%BB%80%E4%B9%88%E6%98%AF%E5%88%86%E7%89%87%E4%B8%8A%E4%BC%A0%E3%80%81%E7%A7%92%E4%BC%A0%E3%80%81%E6%96%AD%E7%82%B9%E7%BB%AD%E4%BC%A0</span><span class="cap desc footnote"></span></div></a></div>

<h3 id="校验"><a href="#校验" class="headerlink" title="校验"></a>校验</h3><p>前端首先计算文件 <code>md5</code> 值，在上传文件前调用接口查询服务器是否存在该文件，如果不存在，直接按业务准备接下来的文件上传；如果存在则跳过该文件的上传并返回可访问的文件 <code>url</code>，以此实现秒传效果；部分存在，需要查找已经上传过的分片，有多种方案可选，这时前端再根据该集合上传未上传的分片即可。</p>
<ul>
<li><p>文件的分片上传记录如果使用磁盘存储，可以通过表查询已经上传的分片数</p>
</li>
<li><p>分片上传通常也可以使用 <code>Redis</code> 来记录，以此来返回需要上传的分片集合</p>
</li>
<li><p>读取 <code>.conf</code> 文件内容，创建的 <code>conf</code> 文件长度为总分片数，每上传一个分块即向 <code>conf</code> 文件中写入一个127，那么没上传的位置就是默认的 0，已上传的就是127</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">List&lt;Integer&gt; uploadedChunks = <span class="keyword">new</span> <span class="title class_">LinkedList</span>&lt;&gt;();</span><br><span class="line"><span class="type">byte</span>[] completeStatusList = Files.readAllBytes(confFile.toPath());</span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; completeStatusList.length; i++) &#123;</span><br><span class="line">    <span class="keyword">if</span> (completeStatusList[i] == Byte.MAX_VALUE) &#123;</span><br><span class="line">        uploadedChunks.add(i);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>上传的文件分片保存时可以通过规律数字命名的方式，通过检查分片是否存在也可得到</p>
</li>
</ul>
<h3 id="上传"><a href="#上传" class="headerlink" title="上传"></a>上传</h3><p>开始执行文件上传，后端用两种方式实现文件写入</p>
<div class="tag-plugin quot"><p class="content" type="icon"><img class="icon prefix lazy" src="" data-src="https://bu.dusays.com/2022/10/24/63567d3e07da3.png" /><span class="text">RandomAccessFile</span><span class="empty"></span></p></div>

<p>Java 除了 File 类之外，还提供了专门处理文件的类，即 <code>RandomAccessFile</code>（随机访问文件）类。</p>
<p>该类是 Java 语言中功能最为丰富的文件访问类，它提供了众多的文件访问方法。<code>RandomAccessFile</code> 类支持“随机访问”方式，这里“随机”是指可以跳转到文件的<strong>任意位置</strong>处读写数据。在访问一个文件的时候，不必把文件从头读到尾，而是希望像访问一个数据库一样“随心所欲”地访问一个文件的某个部分，这时使用 <code>RandomAccessFile</code> 类就是最佳选择。</p>
<p><code>RandomAccessFile</code> 对象类有个<strong>位置指示器</strong>（文件指针），指向当前读写处的位置，当前读写 n 个字节后，文件指示器将指向这 n 个字节后面的下一个字节处。我们可以通过 <code>RandomAccessFile</code> 的 <code>seek(long pos)</code> 方法来设置文件指针的偏移量（距文件开头 <code>pos</code> 个字节处）。如果想要获取文件指针当前的位置的话，可以使用 <code>getFilePointer()</code> 方法。</p>
<p>刚打开文件时，文件指示器指向文件的开头处，可以移动文件指示器到新的位置，随后的读写操作将从新的位置开始。</p>
<p><code>RandomAccessFile</code> 类在数据等长记录格式文件的随机（相对顺序而言）读取时有很大的优势，但该类仅限于<strong>操作文件</strong>，不能访问其他的 I&#x2F;O 设备，如网络、内存映像等。</p>
<details class="tag-plugin colorful folding" color="yellow" child="codeblock" open><summary><span>RandomAccessFile 类的构造方法</span></summary><div class="body"><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 创建随机存储文件流，文件属性由参数File对象指定</span></span><br><span class="line">RandomAccessFile(File file ,  String mode)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 创建随机存储文件流，文件名由参数name指定</span></span><br><span class="line">RandomAccessFile(String name ,  String mode)</span><br></pre></td></tr></table></figure></div></details>

<p>这两个构造方法均涉及到一个 String 类型的参数 <code>mode</code>，它决定随机存储文件流的操作模式，其中 <code>mode</code> 值及对应的含义如下：</p>
<ul>
<li><code>r</code>：以只读的方式打开，调用该对象的任何 write（写）方法都会导致 IOException 异常</li>
<li><code>rw</code>：以读、写方式打开，支持文件的读取或写入。若文件不存在，则创建之。</li>
<li><code>rws</code>：以读、写方式打开，与 <code>rw</code> 不同的是，还要对文件内容的每次更新都同步更新到潜在的存储设备中去。这里的 <code>s</code> 表示synchronous（同步）的意思</li>
<li><code>rwd</code>：以读、写方式打开，与 <code>rw</code> 不同的是，还要对文件内容的每次更新都同步更新到潜在的存储设备中去。使用 <code>rwd</code> 模式仅要求将文件的内容更新到存储设备中，而使用 <code>rws</code> 模式除了更新文件的内容，还要更新文件的元数据（metadata），因此至少要求1次低级别的 I&#x2F;O 操作</li>
</ul>
<p>保存文件分片代码实现</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// try 自动资源管理</span></span><br><span class="line"><span class="keyword">try</span> (<span class="type">RandomAccessFile</span> <span class="variable">randomAccessFile</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">RandomAccessFile</span>(fullFileName, <span class="string">&quot;rw&quot;</span>)) &#123;</span><br><span class="line">    <span class="comment">// 分片大小必须和前端匹配，否则上传会导致文件损坏</span></span><br><span class="line">    <span class="type">long</span> <span class="variable">chunkSize</span> <span class="operator">=</span> dto.getChunkSize() == <span class="number">0L</span> ? defaultChunkSize : dto.getChunkSize().longValue();</span><br><span class="line">    <span class="comment">// 偏移量, 意思是从一个位置开始往文件写入，每一片的大小 * 已经存的块数</span></span><br><span class="line">    <span class="type">long</span> <span class="variable">offset</span> <span class="operator">=</span> chunkSize * (dto.getChunkNumber() - <span class="number">1</span>);</span><br><span class="line">    <span class="comment">// 定位到该分片的偏移量</span></span><br><span class="line">    randomAccessFile.seek(offset);</span><br><span class="line">    <span class="comment">// 写入该分片数据</span></span><br><span class="line">    randomAccessFile.write(dto.getFile().getBytes());</span><br><span class="line">&#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">    log.error(<span class="string">&quot;文件分片上传失败：&quot;</span> + e);</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<div class="tag-plugin quot"><p class="content" type="icon"><img class="icon prefix lazy" src="" data-src="https://bu.dusays.com/2022/10/24/63567d3e07da3.png" /><span class="text">MappedByteBuffer</span><span class="empty"></span></p></div>

<p>java io 操作中通常采用 <code>BufferedReader</code>，<code>BufferedInputStream</code> 等带缓冲的 IO 类处理大文件，不过 java nio 中引入了一种基于 MappedByteBuffer 操作大文件的方式，其读写性能极高，想要深入了解的话可以读一下<a target="_blank" rel="noopener" href="https://blog.csdn.net/zhiyikeji/article/details/128183552">《深入浅出MappedByteBuffer》</a></p>
<blockquote>
<p>如果用的是第三方存储，那么只要调用第三方提供的分片上传 api 即可</p>
</blockquote>
<h3 id="记录分块位置"><a href="#记录分块位置" class="headerlink" title="记录分块位置"></a>记录分块位置</h3><p>服务端创建 <code>.conf</code> 文件用来记录<strong>分块位置</strong>，<code>.conf</code> 文件长度为总分片数，每上传一个分块即向 <code>.conf</code> 文件中写入一个 127，那么没上传的位置就是默认的 0，已上传的就是 <strong>Byte.MAX_VALUE 127</strong></p>
<p>服务器按照请求数据中给的分片序号和每片分块大小（分片大小是固定且一样的）算出开始位置，与读取到的文件片段数据，写入文件。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 是否上传完成</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> dto      文件参数对象</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> confFile .conf 文件</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return</span> true 文件上传完成</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">synchronized</span> <span class="type">boolean</span> <span class="title function_">checkUploadStatus</span><span class="params">(FileChunkDTO dto, File confFile)</span> &#123;</span><br><span class="line">    <span class="keyword">try</span> (<span class="type">RandomAccessFile</span> <span class="variable">confAccessFile</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">RandomAccessFile</span>(confFile, <span class="string">&quot;rw&quot;</span>)) &#123;</span><br><span class="line">        <span class="comment">// 设置文件长度</span></span><br><span class="line">        confAccessFile.setLength(dto.getTotalChunks());</span><br><span class="line">        <span class="comment">// 设置起始偏移量</span></span><br><span class="line">        confAccessFile.seek(dto.getChunkNumber() - <span class="number">1</span>);</span><br><span class="line">        <span class="comment">// 将指定的一个字节写入文件中 127，</span></span><br><span class="line">        confAccessFile.write(Byte.MAX_VALUE);</span><br><span class="line"></span><br><span class="line">        <span class="type">byte</span>[] completeStatusList = Files.readAllBytes(confFile.toPath());</span><br><span class="line">        <span class="comment">// 创建conf文件文件长度为总分片数，每上传一个分块即向conf文件中写入一个127，那么没上传的位置就是默认的0,已上传的就是127</span></span><br><span class="line">        <span class="keyword">for</span> (<span class="type">byte</span> b : completeStatusList) &#123;</span><br><span class="line">            <span class="keyword">if</span> (b != Byte.MAX_VALUE) &#123;</span><br><span class="line">                <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">        log.error(e.getMessage(), e);</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 上传成功记得删除conf文件</span></span><br><span class="line">    confFile.delete();</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="分片全部上传完成"><a href="#分片全部上传完成" class="headerlink" title="分片全部上传完成"></a>分片全部上传完成</h3><p>其实之前的分片一边上传，一边已经做到了<mark class="tag-plugin colorful mark" color="red">文件合并</mark> （每次调用上传接口其实读写的都是同一个 <code>tmp</code> 文件），所以这时的 <code>tmp</code> 文件其实就是完整的原文件，仅仅文件名不同，我们可以多校验一下 <code>md5</code> 值，确保文件没有损坏，确认过后将 <code>tmp</code> 文件重命名即可，至此文件上传全部完成</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 检查md5是否一致</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="type">boolean</span> <span class="title function_">checkFileMd5</span><span class="params">(File tmpFile, String md5)</span> &#123;</span><br><span class="line">    <span class="keyword">try</span> (<span class="type">FileInputStream</span> <span class="variable">fis</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">FileInputStream</span>(tmpFile)) &#123;</span><br><span class="line">        <span class="type">String</span> <span class="variable">checkMd5</span> <span class="operator">=</span> DigestUtils.md5DigestAsHex(fis);</span><br><span class="line">        <span class="keyword">return</span> checkMd5.equals(md5);</span><br><span class="line">    &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">        log.error(<span class="string">&quot;check file md5 error:&quot;</span> + e);</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">RuntimeException</span>(<span class="string">&quot;校验md5值时发生错误&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">cleanUp</span><span class="params">(File tmpFile)</span> &#123;</span><br><span class="line">    <span class="keyword">if</span> (tmpFile.exists()) &#123;</span><br><span class="line">        tmpFile.delete();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">renameFile</span><span class="params">(File tmpFile, String fileName)</span> &#123;</span><br><span class="line">    <span class="comment">// 检查要重命名的文件是否存在，是否是文件</span></span><br><span class="line">    <span class="keyword">if</span> (!tmpFile.exists() || tmpFile.isDirectory()) &#123;</span><br><span class="line">        log.info(<span class="string">&quot;File does not exist: &quot;</span> + tmpFile.getName());</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="type">String</span> <span class="variable">parent</span> <span class="operator">=</span> tmpFile.getParent();</span><br><span class="line">    <span class="type">File</span> <span class="variable">newFile</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">File</span>(parent + File.separator + fileName);</span><br><span class="line">    <span class="comment">// 如果存在, 先删除</span></span><br><span class="line">    <span class="keyword">if</span> (newFile.exists()) &#123;</span><br><span class="line">        newFile.delete();</span><br><span class="line">    &#125;</span><br><span class="line">    tmpFile.renameTo(newFile);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>还有一种处理方案，上传接口每次保存的都是一份 <code>tmp</code> 文件，当分片全部上传完成后需要执行合并分片，这里给出伪代码</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 合并分片</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> chunkFileFolderPath 分片保存目录</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> fileSavePath        文件合并后保存的目录</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> totalChunks         分片数量</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">private</span> <span class="type">boolean</span> <span class="title function_">mergeChunks</span><span class="params">(String chunkFileFolderPath, String fileSavePath, Integer totalChunks)</span> &#123;</span><br><span class="line">    <span class="comment">// 检查分片是否都存在</span></span><br><span class="line">    <span class="keyword">if</span> (<span class="built_in">this</span>.checkChunks(chunkFileFolderPath, totalChunks)) &#123;</span><br><span class="line">        <span class="type">File</span> <span class="variable">chunkFileFolder</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">File</span>(chunkFileFolderPath);</span><br><span class="line">        <span class="type">File</span> <span class="variable">mergeFile</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">File</span>(fileSavePath);</span><br><span class="line">        File[] chunks = chunkFileFolder.listFiles();</span><br><span class="line">        <span class="comment">// 排序</span></span><br><span class="line">        <span class="type">List</span> <span class="variable">fileList</span> <span class="operator">=</span> Arrays.asList(chunks);</span><br><span class="line">        Collections.sort(fileList, (Comparator&lt;File&gt;) (o1, o2) -&gt; &#123;</span><br><span class="line">            <span class="keyword">return</span> Integer.parseInt(o1.getName()) - (Integer.parseInt(o2.getName()));</span><br><span class="line">        &#125;);</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="type">RandomAccessFile</span> <span class="variable">randomAccessFileWriter</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">RandomAccessFile</span>(mergeFile, <span class="string">&quot;rw&quot;</span>);</span><br><span class="line">            <span class="type">byte</span>[] bytes = <span class="keyword">new</span> <span class="title class_">byte</span>[<span class="number">1024</span>];</span><br><span class="line">            <span class="keyword">for</span> (File chunk : chunks) &#123;</span><br><span class="line">                <span class="type">RandomAccessFile</span> <span class="variable">randomAccessFileReader</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">RandomAccessFile</span>(chunk, <span class="string">&quot;r&quot;</span>);</span><br><span class="line">                <span class="type">int</span> len;</span><br><span class="line">                <span class="keyword">while</span> ((len = randomAccessFileReader.read(bytes)) != -<span class="number">1</span>) &#123;</span><br><span class="line">                    randomAccessFileWriter.write(bytes, <span class="number">0</span>, len);</span><br><span class="line">                &#125;</span><br><span class="line">                randomAccessFileReader.close();</span><br><span class="line">            &#125;</span><br><span class="line">            randomAccessFileWriter.close();</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 检查分片是否都存在</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">private</span> <span class="type">boolean</span> <span class="title function_">checkChunks</span><span class="params">(String chunkFileFolderPath, Integer totalChunks)</span> &#123;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">1</span>; i &lt;= totalChunks + <span class="number">1</span>; i++) &#123;</span><br><span class="line">            <span class="comment">// tmp文件命名为 1.tmp、2.tmp</span></span><br><span class="line">            <span class="type">File</span> <span class="variable">file</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">File</span>(chunkFileFolderPath + File.separator + i);</span><br><span class="line">            <span class="keyword">if</span> (!file.exists()) &#123;</span><br><span class="line">                <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="项目运行"><a href="#项目运行" class="headerlink" title="项目运行"></a>项目运行</h2><p>简单实现：<a class="tag-plugin colorful hashtag" color="red" target="_blank" rel="noopener" href="https://gitee.com/coclong/bigfile-upload"><svg t="1701408144765" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="4228" width="200" height="200"><path d="M426.6 64.8c34.8 5.8 58.4 38.8 52.6 73.6l-19.6 117.6h190.2l23-138.6c5.8-34.8 38.8-58.4 73.6-52.6s58.4 38.8 52.6 73.6l-19.4 117.6H896c35.4 0 64 28.6 64 64s-28.6 64-64 64h-137.8l-42.6 256H832c35.4 0 64 28.6 64 64s-28.6 64-64 64h-137.8l-23 138.6c-5.8 34.8-38.8 58.4-73.6 52.6s-58.4-38.8-52.6-73.6l19.6-117.4h-190.4l-23 138.6c-5.8 34.8-38.8 58.4-73.6 52.6s-58.4-38.8-52.6-73.6l19.4-117.8H128c-35.4 0-64-28.6-64-64s28.6-64 64-64h137.8l42.6-256H192c-35.4 0-64-28.6-64-64s28.6-64 64-64h137.8l23-138.6c5.8-34.8 38.8-58.4 73.6-52.6z m11.6 319.2l-42.6 256h190.2l42.6-256h-190.2z" p-id="4229"></path></svg><span>MyGitee</span></a></p>
<blockquote>
<p>为了方便演示使用，本项目使用的是前后端不分离的架构</p>
</blockquote>
<ol>
<li>确认文件上传路径 默认是 <code>F:\tmp</code> 可在 <code>application.yml</code> 中进行修改</li>
<li>连接自己的数据库，导入 <code>sql</code> 目录下面的 <code>db.sql</code>（注意 <code>application.yml</code> 中的数据库名，用户名密码）</li>
<li>分片大小，前后端要对应相同才行（默认是相同的20M不用改）</li>
<li><code>BigfileUploadApplication</code> 是启动类，直接启动即可</li>
<li>启动后访问：<a target="_blank" rel="noopener" href="http://localhost:8080/page/index.html">http://localhost:8080/page/index.html</a></li>
</ol>

<div class="article-footer fs14">
    <section id="references">
      <div class="header"><span>参考资料</span></div>
      <div class="body">
        <ul>
        <li class="post-title">
          <p><a target="_blank" rel="noopener" href="https://blog.csdn.net/zhiyikeji/article/details/128242775">Spring Boot超大文件上传，实现秒传</a></p>

        </li>
        
        <li class="post-title">
          <p><a target="_blank" rel="noopener" href="https://www.bilibili.com/video/BV1aD4y1Y7Co/">大文件分片上传、秒传以及断点续传功能流程以及代码分享</a></p>

        </li>
        </ul>
      </div>
    </section>
    
    <section id="license">
      <div class="header"><span>许可协议</span></div>
      <div class="body"><p>本文采用 <a target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">署名-非商业性使用-相同方式共享 4.0 国际</a> 许可协议，转载请注明出处。</p>
</div>
    </section>
    </div>
</article>
<div class="related-wrap" id="read-next"><section class="body"><div class="item" id="prev"><div class="note">较新文章</div><a href="/2023/10/02/other/%E8%80%83%E9%A9%BE%E7%85%A7%E7%9A%84%E9%82%A3%E4%BA%9B%E4%BA%8B%E5%84%BF/">考驾照的那些事儿</a></div><div class="item" id="next"><div class="note">较早文章</div><a href="/2023/09/07/other/%E6%B8%B8%E9%BE%99%E5%BD%93%E5%BD%92%E6%B5%B7/">游龙当归海，海不迎我自来也</a></div></section></div>

<div class="related-wrap" id="related-posts">
    <section class='header'>
      <div class='title cap theme'>您可能感兴趣的文章</div>
    </section>
    <section class='body'>
    <div class="related-posts"><a class="item" href="\2023\08\13\study\Java代码精简指南\" title="Java代码精简指南"><span class="title">Java代码精简指南</span><span class="excerpt">Java代码精简</span></a><a class="item" href="\2023\11\03\study\23种设计模式\" title="23种设计模式"><span class="title">23种设计模式</span><span class="excerpt">设计模式</span></a></div></section></div>




<footer class="page-footer footnote"><hr><div class="sitemap"><div class="sitemap-group"><span class="fs15">博客</span><a href="/">近期</a><a href="/categories/">分类</a><a href="/tags/">标签</a><a href="/archives/">归档</a></div><div class="sitemap-group"><span class="fs15">项目</span><a href="/wiki/">笔记</a><a target="_blank" rel="noopener" href="https://gitee.com/coclong">开源库</a></div><div class="sitemap-group"><span class="fs15">社交</span><a href="/notes/">友链</a><a href="/">留言板</a><a target="_blank" rel="noopener" href="https://space.bilibili.com/415988557">哔哩哔哩</a></div><div class="sitemap-group"><span class="fs15">更多</span><a href="/more">关于本站</a><a target="_blank" rel="noopener" href="https://gitee.com/coclong">Gitee</a><a target="_blank" rel="noopener" href="https://github.com/Godlike-long">GitHub</a></div></div><div class="text"><p>本站由 <a href="/">sentry</a> 使用 <a target="_blank" rel="noopener" href="https://github.com/xaoxuu/hexo-theme-stellar/tree/1.29.1">Stellar 1.29.1</a> 主题创建。<br>本博客所有文章除特别声明外，均采用 <a target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">CC BY-NC-SA 4.0</a> 许可协议，转载请注明出处。</p>
</div></footer>
<div class="main-mask" onclick="sidebar.dismiss()"></div></div><aside class="l_right">
<div class="widgets">



<widget class="widget-wrapper toc" id="data-toc" collapse="false"><div class="widget-header dis-select"><span class="name">本文目录</span><a class="cap-action" onclick="sidebar.toggleTOC()" ><svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 6h11m-11 6h11m-11 6h11M4 6h1v4m-1 0h2m0 8H4c0-1 2-2 2-3s-1-1.5-2-1"/></svg></a></div><div class="widget-body"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BB%8B%E7%BB%8D"><span class="toc-text">介绍</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%88%86%E7%89%87%E4%B8%8A%E4%BC%A0"><span class="toc-text">分片上传</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%96%AD%E7%82%B9%E7%BB%AD%E4%BC%A0"><span class="toc-text">断点续传</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%A0%B8%E5%BF%83%E9%80%BB%E8%BE%91"><span class="toc-text">核心逻辑</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%A7%92%E4%BC%A0"><span class="toc-text">秒传</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%8F%82%E6%95%B0%E8%AE%BE%E8%AE%A1"><span class="toc-text">参数设计</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%B5%81%E7%A8%8B%E8%AE%BE%E8%AE%A1"><span class="toc-text">流程设计</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%A0%A1%E9%AA%8C"><span class="toc-text">校验</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%B8%8A%E4%BC%A0"><span class="toc-text">上传</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%AE%B0%E5%BD%95%E5%88%86%E5%9D%97%E4%BD%8D%E7%BD%AE"><span class="toc-text">记录分块位置</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%88%86%E7%89%87%E5%85%A8%E9%83%A8%E4%B8%8A%E4%BC%A0%E5%AE%8C%E6%88%90"><span class="toc-text">分片全部上传完成</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%A1%B9%E7%9B%AE%E8%BF%90%E8%A1%8C"><span class="toc-text">项目运行</span></a></li></ol></div><div class="widget-footer">

<a class="top" onclick="util.scrollTop()"><svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24"><g fill="none" stroke="currentColor" stroke-width="1.5"><path d="M2 12c0-4.714 0-7.071 1.464-8.536C4.93 2 7.286 2 12 2c4.714 0 7.071 0 8.535 1.464C22 4.93 22 7.286 22 12c0 4.714 0 7.071-1.465 8.535C19.072 22 16.714 22 12 22s-7.071 0-8.536-1.465C2 19.072 2 16.714 2 12Z"/><path stroke-linecap="round" stroke-linejoin="round" d="m9 15.5l3-3l3 3m-6-4l3-3l3 3"/></g></svg><span>回到顶部</span></a></div></widget>
</div></aside><div class='float-panel blur'>
  <button type='button' style='display:none' class='laptop-only rightbar-toggle mobile' onclick='sidebar.rightbar()'>
    <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 6h11m-11 6h11m-11 6h11M4 6h1v4m-1 0h2m0 8H4c0-1 2-2 2-3s-1-1.5-2-1"/></svg>
  </button>
  <button type='button' style='display:none' class='mobile-only leftbar-toggle mobile' onclick='sidebar.leftbar()'>
    <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24"><g fill="none" stroke="currentColor" stroke-width="1.5"><path d="M2 11c0-3.771 0-5.657 1.172-6.828C4.343 3 6.229 3 10 3h4c3.771 0 5.657 0 6.828 1.172C22 5.343 22 7.229 22 11v2c0 3.771 0 5.657-1.172 6.828C19.657 21 17.771 21 14 21h-4c-3.771 0-5.657 0-6.828-1.172C2 18.657 2 16.771 2 13z"/><path id="sep" stroke-linecap="round" d="M5.5 10h6m-5 4h4m4.5 7V3"/></g></svg>
  </button>
</div>
</div><div class="scripts">
<script type="text/javascript">
  const ctx = {
    date_suffix: {
      just: `刚刚`,
      min: `分钟前`,
      hour: `小时前`,
      day: `天前`,
    },
    root : `/`,
  };

  // required plugins (only load if needs)
  if (`local_search`) {
    ctx.search = {};
    ctx.search.service = `local_search`;
    if (ctx.search.service == 'local_search') {
      let service_obj = Object.assign({}, `{"field":"all","path":"/search.json","content":true,"sort":"-date"}`);
      ctx.search[ctx.search.service] = service_obj;
    }
  }
  const def = {
    avatar: `https://gcore.jsdelivr.net/gh/cdn-x/placeholder@1.0.12/avatar/round/3442075.svg`,
    cover: `https://gcore.jsdelivr.net/gh/cdn-x/placeholder@1.0.12/cover/76b86c0226ffd.svg`,
  };
  const deps = {
    jquery: `https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js`,
    marked: `https://cdn.jsdelivr.net/npm/marked@13.0.1/lib/marked.umd.min.js`
  }
  

</script>

<script type="text/javascript">
  const utils = {
    // 懒加载 css https://github.com/filamentgroup/loadCSS
    css: (href, before, media, attributes) => {
      var doc = window.document;
      var ss = doc.createElement("link");
      var ref;
      if (before) {
        ref = before;
      } else {
        var refs = (doc.body || doc.getElementsByTagName("head")[0]).childNodes;
        ref = refs[refs.length - 1];
      }
      var sheets = doc.styleSheets;
      if (attributes) {
        for (var attributeName in attributes) {
          if (attributes.hasOwnProperty(attributeName)) {
            ss.setAttribute(attributeName, attributes[attributeName]);
          }
        }
      }
      ss.rel = "stylesheet";
      ss.href = href;
      ss.media = "only x";
      function ready(cb) {
        if (doc.body) {
          return cb();
        }
        setTimeout(function () {
          ready(cb);
        });
      }
      ready(function () {
        ref.parentNode.insertBefore(ss, before ? ref : ref.nextSibling);
      });
      var onloadcssdefined = function (cb) {
        var resolvedHref = ss.href;
        var i = sheets.length;
        while (i--) {
          if (sheets[i].href === resolvedHref) {
            return cb();
          }
        }
        setTimeout(function () {
          onloadcssdefined(cb);
        });
      };
      function loadCB() {
        if (ss.addEventListener) {
          ss.removeEventListener("load", loadCB);
        }
        ss.media = media || "all";
      }
      if (ss.addEventListener) {
        ss.addEventListener("load", loadCB);
      }
      ss.onloadcssdefined = onloadcssdefined;
      onloadcssdefined(loadCB);
      return ss;
    },

    js: (src, opt) => new Promise((resolve, reject) => {
      var script = document.createElement('script');
      if (src.startsWith('/')){
        src = ctx.root + src.substring(1);
      }
      script.src = src;
      if (opt) {
        for (let key of Object.keys(opt)) {
          script[key] = opt[key]
        }
      } else {
        // 默认异步，如果需要同步，第二个参数传入 {} 即可
        script.async = true
      }
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    }),

    jq: (fn) => {
      if (typeof jQuery === 'undefined') {
        utils.js(deps.jquery).then(fn)
      } else {
        fn()
      }
    },
    
    onLoading: (el) => {
      if (el) {
        $(el).append('<div class="loading-wrap"><svg xmlns="http://www.w3.org/2000/svg" width="2em" height="2em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 24 24"><g fill="none" stroke="currentColor" stroke-linecap="round" stroke-width="2"><path stroke-dasharray="60" stroke-dashoffset="60" stroke-opacity=".3" d="M12 3C16.9706 3 21 7.02944 21 12C21 16.9706 16.9706 21 12 21C7.02944 21 3 16.9706 3 12C3 7.02944 7.02944 3 12 3Z"><animate fill="freeze" attributeName="stroke-dashoffset" dur="1.3s" values="60;0"/></path><path stroke-dasharray="15" stroke-dashoffset="15" d="M12 3C16.9706 3 21 7.02944 21 12"><animate fill="freeze" attributeName="stroke-dashoffset" dur="0.3s" values="15;0"/><animateTransform attributeName="transform" dur="1.5s" repeatCount="indefinite" type="rotate" values="0 12 12;360 12 12"/></path></g></svg></div>');
      }
    },
    onLoadSuccess: (el) => {
      if (el) {
        $(el).find('.loading-wrap').remove();
      }
    },
    onLoadFailure: (el) => {
      if (el) {
        $(el).find('.loading-wrap svg').remove();
        $(el).find('.loading-wrap').append('<svg xmlns="http://www.w3.org/2000/svg" width="2em" height="2em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 24 24"><g fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"><path stroke-dasharray="60" stroke-dashoffset="60" d="M12 3L21 20H3L12 3Z"><animate fill="freeze" attributeName="stroke-dashoffset" dur="0.5s" values="60;0"/></path><path stroke-dasharray="6" stroke-dashoffset="6" d="M12 10V14"><animate fill="freeze" attributeName="stroke-dashoffset" begin="0.6s" dur="0.2s" values="6;0"/></path></g><circle cx="12" cy="17" r="1" fill="currentColor" fill-opacity="0"><animate fill="freeze" attributeName="fill-opacity" begin="0.8s" dur="0.4s" values="0;1"/></circle></svg>');
        $(el).find('.loading-wrap').addClass('error');
      }
    },
    request: (el, url, callback, onFailure) => {
      let retryTimes = 3;
      utils.onLoading(el);
      function req() {
        return new Promise((resolve, reject) => {
          let status = 0; // 0 等待 1 完成 2 超时
          let timer = setTimeout(() => {
            if (status === 0) {
              status = 2;
              timer = null;
              reject('请求超时');
              if (retryTimes == 0) {
                onFailure();
              }
            }
          }, 5000);
          fetch(url).then(function(response) {
            if (status !== 2) {
              clearTimeout(timer);
              resolve(response);
              timer = null;
              status = 1;
            }
            if (response.ok) {
              return response.json();
            }
            throw new Error('Network response was not ok.');
          }).then(function(data) {
            retryTimes = 0;
            utils.onLoadSuccess(el);
            callback(data);
          }).catch(function(error) {
            if (retryTimes > 0) {
              retryTimes -= 1;
              setTimeout(() => {
                req();
              }, 5000);
            } else {
              utils.onLoadFailure(el);
              onFailure();
            }
          });
        });
      }
      req();
    },
  };
</script>

<script>
  const sidebar = {
    leftbar: () => {
      if (l_body) {
        l_body.toggleAttribute('leftbar');
        l_body.removeAttribute('rightbar');
      }
    },
    rightbar: () => {
      if (l_body) {
        l_body.toggleAttribute('rightbar');
        l_body.removeAttribute('leftbar');
      }
    },
    dismiss: () => {
      if (l_body) {
        l_body.removeAttribute('leftbar');
        l_body.removeAttribute('rightbar');
      }
    },
    toggleTOC: () => {
      document.querySelector('#data-toc').classList.toggle('collapse');
    }
  }
</script>
<script type="text/javascript">
  (() => {
    const tagSwitchers = document.querySelectorAll('.tag-subtree.parent-tag > a > .tag-switcher-wrapper')
    for (const tagSwitcher of tagSwitchers) {
      tagSwitcher.addEventListener('click', (e) => {
        const parent = e.target.closest('.tag-subtree.parent-tag')
        parent.classList.toggle('expanded')
        e.preventDefault()
      })
    }

    // Get active tag from query string, then activate it.
    const urlParams = new URLSearchParams(window.location.search)
    const activeTag = urlParams.get('tag')
    if (activeTag) {
      let tag = document.querySelector(`.tag-subtree[data-tag="${activeTag}"]`)
      if (tag) {
        tag.querySelector('a').classList.add('active')
        
        while (tag) {
          tag.classList.add('expanded')
          tag = tag.parentElement.closest('.tag-subtree.parent-tag')
        }
      }
    }
  })()
</script>


<!-- required -->
<script src="/js/main.js?v=1.29.1" defer></script>

<script type="text/javascript">
  const applyTheme = (theme) => {
    if (theme === 'auto') {
      document.documentElement.removeAttribute('data-theme')
    } else {
      document.documentElement.setAttribute('data-theme', theme)
    }

    applyThemeToGiscus(theme)
  }

  const applyThemeToGiscus = (theme) => {
    theme = theme === 'auto' ? 'preferred_color_scheme' : theme

    const cmt = document.getElementById('giscus')
    if (cmt) {
      // This works before giscus load.
      cmt.setAttribute('data-theme', theme)
    }

    const iframe = document.querySelector('#comments > section.giscus > iframe')
    if (iframe) {
      // This works after giscus loaded.
      const src = iframe.src
      const newSrc = src.replace(/theme=[\w]+/, `theme=${theme}`)
      iframe.src = newSrc
    }
  }

  const switchTheme = () => {
    // light -> dark -> auto -> light -> ...
    const currentTheme = document.documentElement.getAttribute('data-theme')
    let newTheme;
    switch (currentTheme) {
      case 'light':
        newTheme = 'dark'
        break
      case 'dark':
        newTheme = 'auto'
        break
      default:
        newTheme = 'light'
    }
    applyTheme(newTheme)
    window.localStorage.setItem('Stellar.theme', newTheme)

    const messages = {
      light: `切换到浅色模式`,
      dark: `切换到深色模式`,
      auto: `切换到跟随系统配色`,
    }
    hud?.toast?.(messages[newTheme])
  }

  (() => {
    // Apply user's preferred theme, if any.
    const theme = window.localStorage.getItem('Stellar.theme')
    if (theme !== null) {
      applyTheme(theme)
    }
  })()
</script>


<!-- optional -->



<script defer>
  window.addEventListener('DOMContentLoaded', (event) => {
    ctx.services = Object.assign({}, JSON.parse(`{"mdrender":{"js":"/js/services/mdrender.js"},"siteinfo":{"js":"/js/services/siteinfo.js","api":null},"ghinfo":{"js":"/js/services/ghinfo.js"},"sites":{"js":"/js/services/sites.js"},"friends":{"js":"/js/services/friends.js"},"timeline":{"js":"/js/services/timeline.js"},"fcircle":{"js":"/js/services/fcircle.js"},"weibo":{"js":"/js/services/weibo.js"},"memos":{"js":"/js/services/memos.js"}}`));
    for (let id of Object.keys(ctx.services)) {
      const js = ctx.services[id].js;
      if (id == 'siteinfo') {
        ctx.cardlinks = document.querySelectorAll('a.link-card[cardlink]');
        if (ctx.cardlinks?.length > 0) {
          utils.js(js, { defer: true }).then(function () {
            setCardLink(ctx.cardlinks);
          });
        }
      } else {
        const els = document.getElementsByClassName(`ds-${id}`);
        if (els?.length > 0) {
          utils.jq(() => {
            if (id == 'timeline' || 'memos' || 'marked') {
              utils.js(deps.marked).then(function () {
                utils.js(js, { defer: true });
              });
            } else {
              utils.js(js, { defer: true });
            }
          });
        }
      }
    }
  });
</script>

<script>
  window.addEventListener('DOMContentLoaded', (event) => {
    ctx.search = {
      path: `/search.json`,
    }
    utils.js('/js/search/local-search.js', { defer: true });
  });
</script><script>
  window.FPConfig = {
    delay: 0,
    ignoreKeywords: [],
    maxRPS: 5,
    hoverDelay: 25
  };
</script>
<script defer src="https://cdn.jsdelivr.net/npm/flying-pages@2/flying-pages.min.js"></script><script defer src="https://cdn.jsdelivr.net/npm/vanilla-lazyload@19.1.3/dist/lazyload.min.js"></script>
<script>
  // https://www.npmjs.com/package/vanilla-lazyload
  // Set the options globally
  // to make LazyLoad self-initialize
  window.lazyLoadOptions = {
    elements_selector: ".lazy",
  };
  // Listen to the initialization event
  // and get the instance of LazyLoad
  window.addEventListener(
    "LazyLoad::Initialized",
    function (event) {
      window.lazyLoadInstance = event.detail.instance;
    },
    false
  );
  document.addEventListener('DOMContentLoaded', function () {
    window.lazyLoadInstance?.update();
  });
</script><script>
  ctx.fancybox = {
    selector: `.timenode p>img`,
    css: `https://cdn.jsdelivr.net/npm/@fancyapps/ui@5.0/dist/fancybox/fancybox.css`,
    js: `https://cdn.jsdelivr.net/npm/@fancyapps/ui@5.0/dist/fancybox/fancybox.umd.js`
  };
  var selector = '[data-fancybox]:not(.error)';
  if (ctx.fancybox.selector) {
    selector += `, ${ctx.fancybox.selector}`
  }
  var needFancybox = document.querySelectorAll(selector).length !== 0;
  if (!needFancybox) {
    const els = document.getElementsByClassName('ds-memos');
    if (els != undefined && els.length > 0) {
      needFancybox = true;
    }
  }
  if (needFancybox) {
    utils.css(ctx.fancybox.css);
    utils.js(ctx.fancybox.js, { defer: true }).then(function () {
      Fancybox.bind(selector, {
        hideScrollbar: false,
        Thumbs: {
          autoStart: false,
        },
        caption: (fancybox, slide) => {
          return slide.triggerEl.alt || slide.triggerEl.dataset.caption || null
        }
      });
    })
  }
</script>
<script>
  window.addEventListener('DOMContentLoaded', (event) => {
    const swiper_api = document.getElementById('swiper-api');
    if (swiper_api != undefined) {
      utils.css(`https://unpkg.com/swiper@10.3.1/swiper-bundle.min.css`);
      utils.js(`https://unpkg.com/swiper@10.3.1/swiper-bundle.min.js`, { defer: true }).then(function () {
        const effect = swiper_api.getAttribute('effect') || '';
        var swiper = new Swiper('.swiper#swiper-api', {
          slidesPerView: 'auto',
          spaceBetween: 8,
          centeredSlides: true,
          effect: effect,
          rewind: true,
          pagination: {
            el: '.swiper-pagination',
            clickable: true,
          },
          navigation: {
            nextEl: '.swiper-button-next',
            prevEl: '.swiper-button-prev',
          },
        });
      })
    }
  });
</script>
<script>
  document.addEventListener('DOMContentLoaded', function () {
    window.codeElements = document.querySelectorAll('.code');
    if (window.codeElements.length > 0) {
      ctx.copycode = {
        default_text: `Copy`,
        success_text: `Copied`,
        toast: `复制成功`,
      };
      utils.js('/js/plugins/copycode.js');
    }
  });
</script>


<!-- inject -->

</div></body></html>
